import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * author: MaHX
 * date: 2019/9/19/17:36
 * description:
 **/
public class TestReadAndWriteLock {
    public static void main(String args[]){
        final ReadAndWriteDemo readAndWriteDemo = new ReadAndWriteDemo();
        new Thread(new Runnable() {
            @Override
            public void run() {
                readAndWriteDemo.setNumber((int)(Math.random()*101));
            }
        },"写").start();

        for (int i = 0; i < 100; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    readAndWriteDemo.getNumber();
                }
            }).start();
        }
    }

    public static class ReadAndWriteDemo{
        private int number = 0;
        private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

        public void getNumber() {
            readWriteLock.readLock().lock();
            try{
                System.out.println(Thread.currentThread().getName()+" 读: "+number);
            }finally {
                readWriteLock.readLock().unlock();
            }
        }

        public void setNumber(int number) {
            readWriteLock.writeLock().lock();
            try{
                this.number = number;
                System.out.println(Thread.currentThread().getName()+" 写入: "+number);
            }finally {
                readWriteLock.writeLock().unlock();
            }

        }
    }
}
